<?php

Raise::load('core.ui.RaiseUIControl');
Raise::load('core.ui.RaisePagination');

/**
 * PaginatedList UIControl
 * A list with pagination
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @abstract
 * @package phpraise.control
 * @since 1.2
 */
abstract class PaginatedList extends RaiseUIControl {

    /**
     *
     * @var RaiseDbConnection
     */
    protected $connection;

    private $perPage;

    private $pageNo;

    private $count;

    private $url;

    private $showPaging = true;

    public function __construct($conn){
        $this->connection = $conn;
    }

    /**
     * Get or set the number of items per page
     * @param integer $p (optional) Set the number of items to display per page
     * @return integer
     */
    public function perPage($p = null){
        if(func_num_args() == 1){
            $this->perPage = $p;
        }
        return $this->perPage;
    }

    /**
     * Get or set the page number, starting from 1
     * @param integer $p (optional) Set the page number
     * @return integer
     */
    public function pageNo($p = null){
        if(func_num_args() == 1){
            $this->pageNo = $p;
        }
        return $this->pageNo ? $this->pageNo : 1;
    }

    /**
     * Get or set the item count
     * @param integer $c (optional) Set the item count
     * @return integer
     */
    public function count($c = null){
        if(func_num_args() == 1){
            $this->count = $c;
        }
        return $this->count;
    }

    /**
     * Get or set URL template for this pagination list
     * @param string|RaiseUrl $u (optional) Set the new URL template
     * @return string|RaiseUrl
     */
    public function url($u = null){
        if(func_num_args() == 1){
            $this->url = $u;
        }
        return $this->url;
    }

    /**
     * Get or set whether pagination will be shown or not
     * @param boolean $s (optional) Set whether pagination will be shown or not
     * @return boolean
     */
    public function showPaging($s = null){
        if(func_num_args() == 1){
            $this->showPaging = $s;
        }
        return $this->showPaging;
    }
    
    public function output(){
        if($this->perPage() > 0 && $this->showPaging()){
            $p = new RaisePagination($this->url());
            $p->current($this->pageNo());
            $p->itemsPerPage($this->perPage());
            $p->totalItem($this->count());
            if($p->totalPages() > 0 && $this->pageNo() > $p->totalPages()){
                $this->page()->application()->response()->redirect('/'.sprintf($this->url(), 1));
            }
            return $p->html()->__toString();
        }
        return '';
    }

}